package biz.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import system.StaticData;

/**
 * 工具类
 * 
 * @author lcy 2010-10-30
 */
public final class YwsOLUtil {

	private static SimpleDateFormat dateFormater = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public static Map<String, String> GetHTMLandSessionIDByURL(
			String urlAddress, String cookie) {

		Map<String, String> map = new HashMap<String, String>();
		try {
			URL url = new URL(urlAddress);

			HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();

			if (cookie != null)
				urlcon.setRequestProperty("Cookie", cookie);

			InputStream in = urlcon.getInputStream();

			String responseURL = urlcon.getURL().toString();

			String cookieURL = null;
			if (responseURL.indexOf(";jsessionid=") > 0) {
				cookieURL = (responseURL
						.substring(responseURL.indexOf(";") + 1) + "; ")
						.toUpperCase();
			}

			String set_cookie = urlcon.getHeaderField("Set-Cookie");

			if (cookieURL == null)
				map.put("sessionid", set_cookie);
			else if (set_cookie == null)
				map.put("sessionid", cookieURL);
			else
				map.put("sessionid", cookieURL + set_cookie);

			int all = in.available();
			String webpage = null;
			while (all > 0) {
				byte[] b = new byte[all];
				in.read(b);
				webpage = new String(b, "UTF-8");

				all = in.available();
				// Thread.sleep(2000);// 给它点下载的时间，每两秒钟读取一次
			}
			in.close();

			// Thread.sleep(3500); // 测试时使用
			map.put("html", webpage);
			return map;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * @param urlAddress
	 *            要访问的URL地址
	 * @return 该URL的HTML
	 */
	public static String GetHTMLByURL(String urlAddress, String cookie) {
		URL url = null;
		try {
			url = new URL(urlAddress);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}

		HttpURLConnection urlcon = null;
		InputStream in = null;
		BufferedReader reader = null;
		try {
			urlcon = (HttpURLConnection) url.openConnection();
			if (cookie != null)
				urlcon.setRequestProperty("Cookie", cookie);

			in = urlcon.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

			StringBuffer sb = new StringBuffer("");
			String temp = null;
			while ((temp = reader.readLine()) != null) {
				// temp=new String(reader.readLine().getBytes("gbk");
				sb.append(temp);
				sb.append("\n");

			}

			return sb.toString();
			/*
			 * InputStream in = urlcon.getInputStream(); int all =
			 * in.available(); String webpage = null; while (all > 0) { byte[] b
			 * = new byte[all]; in.read(b); webpage = new String(b, "UTF-8");
			 * all = in.available();
			 * 
			 * } in.close(); // Thread.sleep(3500); // 测试时使用 return webpage;
			 */
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (in != null)
					in.close();
				if (reader != null)
					reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		// 老代码，有编码问题
		/*
		 * URLConnection urlcon = null; InputStream in = null; try { urlcon =
		 * url.openConnection(); if (cookie != null)
		 * urlcon.setRequestProperty("Cookie", cookie);
		 * 
		 * in = urlcon.getInputStream(); int all = in.available();
		 * 
		 * BufferedReader reader = new BufferedReader( new
		 * InputStreamReader(in)); StringBuffer sb = new StringBuffer("");
		 * String a = null;
		 * 
		 * while ((a = reader.readLine()) != null) sb.append(a + "\n");
		 * 
		 * in.close(); return sb.toString();
		 */

	}

	public static void DownloadByURL(String urlAddress, String referer, String cookie, String localPath) {

		URL url = null;
		try {
			url = new URL(urlAddress);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		URLConnection urlcon = null;
		InputStream in = null;
		try {
			urlcon = url.openConnection();
			if (cookie != null)
				urlcon.setRequestProperty("Cookie", cookie);
			if (referer != null)
				urlcon.setRequestProperty("Referer", referer);
			
			in = urlcon.getInputStream();

			OutputStream os = new FileOutputStream(localPath);

			byte[] buffer = new byte[1024];
			int byteReaded = in.read(buffer);
			while (byteReaded != -1) {
				os.write(buffer, 0, byteReaded);
				byteReaded = in.read(buffer);
			}

			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	
	
	/***
	 * 读取配置文件所有值
	 * 
	 * @return 键值对
	 */
	public static Map<String, String> ReadPropertiesFromFile() {

		Properties props = new Properties();

		try {
			InputStream infile = YwsOLUtil.class.getResourceAsStream("/system.properties");

			InputStream ips = new BufferedInputStream(infile);
			props.load(ips);

			Map<String, String> properties = new HashMap<String, String>();
			for (String propertyname : props.stringPropertyNames())
				properties.put(propertyname, props.getProperty(propertyname));

			return properties;

		} catch (IOException ie) {
			ie.printStackTrace();
			return null;
		}

	}

	/***
	 * MD5加密
	 * 
	 * @param 要加密的字符串
	 * @return 加密后的哈希值
	 */
	public static String EncryptToMD5(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}

	/***
	 * 判断字符串是否为合法IP
	 * 
	 * @param strIP
	 */
	public static boolean IsIP(String strIP) {
		if (strIP == null)
			return false;

		// String ipRegex =
		// "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		try {
			// String ipRegex = "^[1,255]\\.[1,255]\\.[1,255]\\.[1,255]$";
			String ipRegex = "^((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)(\\.((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)){3}$";
			// 参考：http://blog.csdn.net/SeaWave/archive/2007/03/05/1520988.aspx
			return strIP.matches(ipRegex);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	/***
	 * 获取指定特征码的字符串
	 * 
	 * @return
	 */
	public static String GetFromStringByBeforeAfter(String allStr, String beforeStr, String afterStr, boolean isStartAtBefore) {
		// iaryBook.yws?id=83339" target="_blank">[我的日记本]</
		int beforeIndex = -1;
		int afterIndex = -1;
		try {
			if (isStartAtBefore) {
				beforeIndex = allStr.indexOf(beforeStr);
				if (beforeIndex < 0)
					return null;
			} else {
				afterIndex = allStr.indexOf(afterStr);
				if (afterIndex < 0)
					return null;
			}

			
			if (isStartAtBefore)
				afterIndex = allStr.indexOf(afterStr, beforeIndex+1);
			else
				beforeIndex = allStr.lastIndexOf(beforeStr, afterIndex - 1);

			beforeIndex += beforeStr.length() - 1;
			
			return allStr.substring(beforeIndex + 1, afterIndex);
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static String GetNowTime() {
		return dateFormater.format(new Date());
	}
}
